<!-- （张仕琪）注册页面 -->
<template>
  <div class="body_sty">
    <div class="regist_title">用户注册</div>
    <!--@用于监听事件，@submit 校验通过后的提交表单事件，@failed 是表单校验失败后的事件-->
    <!-- 在表单中，每个 Field 组件 代表一个表单项，使用 Field 的 rules 属性定义校验规则。 -->
    <van-form @submit="regist" @failed="onFailed" class="regist_sty">
      <van-cell-group>
        <van-field required v-model="user.userTel" type="tel" label="手机号" :rules="[
          { required: true, message: '请填手机号！' },
          { validator: isMobile, message: '手机号格式不正确！' },
        ]" />
        <van-field required v-model="user.verifyCode" maxlength="5" label="验证码">
          <template #right-icon>
            <van-image width="100" height="40" style="margin-left: 10px" :src="kapchaSrc" @click="flushKaptch" />
          </template>
        </van-field>
        <van-field required v-model="user.smsCode" label="短信验证码">
          :rules="[ { required: true, message: '请填短信验证码！' }]"
          <template #button>
            <van-button size="small" type="primary" @click="sendSmsCode">发送验证码</van-button>
          </template>
        </van-field>
        <van-field required v-model="user.userIdCard" label="身份证号码" :rules="[
          { required: true, message: '请填身份证号！' },
          { validator: isIdCard, message: '身份证号格式不正确！' },
        ]" />
        <van-field required v-model="user.userName" label="真实姓名" :rules="[{ required: true, message: '请填真实姓名！' }]" />
        <van-field required v-model="user.userPassword" type="password" label="密码"
          :rules="[{ required: true, message: '请填密码！' }]" />
        <van-field required v-model="user.rePassword" type="password" label="确认密码" :rules="[
          { required: true, message: '请确认密码！' },
          { validator: validPassword, message: '两次密码不一致，请重新输入！' },
        ]" />
        <van-checkbox v-model="checked" class="van-field">
          <a>阅读《用户协议与隐私政策》</a>
        </van-checkbox>
        <!-- <van-button type="primary" block round class="regist_btn" @click="regist" :disabled="btnRegistIsUse">注 &nbsp; 册</van-button> -->

        <van-button type="primary" block round class="regist_btn" native-type="submit" :disabled="btnRegistIsUse">
          注 &nbsp; 册</van-button>

        <div style="text-align: right; margin: 10px">
          <a href="#" @click="toLoginView">已有帐号，立即登录？</a>
        </div>
      </van-cell-group>
    </van-form>
    <div class="down">
      <img src="../assets/img/xiaomao.gif" class="img_sty">
    </div>
  </div>
</template>
<script setup>
//import axios from 'axios';
import http from "@/utils/request.js";
import { isMobile, isIdCard } from "@/utils/validate.js";
import { useRouter } from "vue-router";
import { Toast, Notify } from "vant";
import { reactive, ref, onMounted, computed } from "vue";
const router = useRouter(); //获取到router 对象，用于编程式跳转导航
const kapchaSrc = ref("");
const checked = ref(false);

const user = reactive({
  userTel: "", //这个要和实体类的名字一模一样
  verifyCode: "",
  smsCode: "",
  userIdCard: "",
  userName: "",
  userPassword: "",
  rePassword: "",
  uuid: "",
});

function flushKaptch() {
  http
    .get("/user/kaptcha?d=" + Date.now())
    .then(function (response) {
      console.log(response);
      kapchaSrc.value = "data:image/gif;base64," + response.data.data.img;
      user.uuid = response.data.data.uuid;
    })
    .catch(function (error) {
      console.log(error);
    });
}

function sendSmsCode() {
  if (user.userTel && user.verifyCode) {
    http
      .get("/user/smscode", {
        params: {
          d: Date.now(),
          userTel: user.userTel,
          uuid: user.uuid,
          verifyCode: user.verifyCode,
        },
      })
      .then(function (response) {
        console.log("发送短信验证码", response);
        if (response.data.resCode === "200") {
          //http响应状态码为200时
          //成功通知
          Notify({ type: "success", message: "短信发送成功！" });
        } else {
          //危险通知
          Notify({ type: "danger", message: response.data.resDesc });
        }
      })
      .catch(function (error) {
        //http响应状态码不为200时
        console.log("发送短信验证码", error);
        //危险通知
        Notify({ type: "danger", message: "请求失败！" });
      });
  } else {
    Toast("请输入手机号、图片验证码");
  }
}

// function validPhone(val) {
//     console.log('手机号校验函数接收到的数据：',val);
//     if (!val || val.length != 11) {
//         return false;
//     }
//     return true;
// }

// function validIdCard(val) {
//     console.log('身份证号校验函数接收到的数据：',val);
//     if (!val || val.length != 18) {
//         return false;
//     }

// }

// function validatePassword( value) {
//     console.log('身份证号校验函数接收到的数据：',value);
//   if (value.length < 6) {
//     return false
//   }
//   return true;
// }

const validPassword = (val) => user.userPassword === val;

const onFailed = (errorInfo) => {
  console.log("failed:表单校验失败", errorInfo);
};

function regist() {
  http
    .post("/user/register", user) //后端的地址
    .then(function (res) {
      console.log("用户注册结果，", res);
      if (res.data.resCode === "200") {
        Notify({ type: "success", message: "注册成功！" });
        setTimeout(() => {
          //1000毫秒之后跳转至登录页面;
          router.push("/login");
        }, 1000);
      } else {
        Notify({ type: "danger", message: res.data.resDesc });
      }
    })
    .catch(function (res) {
      //注册发送异常
      Notify({ type: "danger", message: "系统异常！" });
    });
}

//跳转到登录页面
function toLoginView() {
  router.push("/login");
}

//注册按钮的可用状态
const btnRegistIsUse = computed(() => !checked.value);

onMounted(() => {
  //生命周其钩子函资数,用于组件挂钱完成之后执行一些任务
  flushKaptch();
});
</script>

<style scoped>
.regist_title {
  font-size: 25px;
  text-align: center;
  margin-top: 30px;
  margin-bottom: 20px;
  margin-left: 25px;
  font-weight: 800;
  letter-spacing: 0.5rem;
  color: blueviolet;
}

.van-field {
  padding: 16px 15px;
}

.regist_btn {
  font-size: 20px;
  margin-top: 20px;
  width: 70%;
  position: relative;
  margin: auto;
}

.img_sty {
  /* margin-left: 30px; */
  height: 100px;
  width: 100x;
  position: absolute;
  animation-name: example;
  animation-duration: 5s;
  animation-timing-function: ease-in;
  animation-iteration-count: infinite;
}

@keyframes example {
  0% {
    right: 0px;
  }

  /* 25%  { right:80px; } */
  50% {
    right: 150px;
  }

  /* 75%  { right:200px; } */
  100% {
    right: 360px;
  }
}

.body_sty {
  background-color: #fef0da;
  position: absolute;
  height: auto;
}

.down {
  height: 107px;
  position: relative;
  background-color: fef0da;
}

.regist_sty {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
